import axios, {
  type AxiosError,
  type InternalAxiosRequestConfig,
  type AxiosResponse,
  type AxiosInstance,
  type AxiosRequestConfig,
  type Method,
} from "axios";

const axiosapi: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
});

// 添加请求拦截器
axiosapi.interceptors.request.use(
  function (config: InternalAxiosRequestConfig) {
    // 在发送请求之前做些什么
    return config;
  },
  function (error: AxiosError) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axiosapi.interceptors.response.use(
  function (response: AxiosResponse) {
    // 对响应数据做点什么
    return response;
  },
  function (error: AxiosError) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

type DataType<T = any> = {
  code: number;
  data: T;
  message: string;
};

const request = <T = any>(
  url: string,
  method: Method = "get",
  data?: Object,
  options?: AxiosRequestConfig
) => {
  return axiosapi.request<T, DataType<T>>({
    url,
    [method === "GET" ? "params" : "data"]: data,
    method,
    ...options,
  });
};

// 封装请求
export const get = <T = any>(url: string, data: object) => {
  request<T>(url, "GET", data);
};
export const post = <T = any>(url: string, data: object) => {
  request<T>(url, "POST", data);
};
export const put = <T = any>(url: string, data: object) => {
  request<T>(url, "PUT", data);
};
export const del = <T = any>(url: string, data: object) => {
  request<T>(url, "DELETE", data);
};


export default axiosapi;
